import tkinter as tk
import pygame
import json
import io
from base64 import b64decode

# 初始化音频系统
pygame.mixer.init()

def load_sound_data():
    """从JSON文件加载音频数据"""
    try:
        with open("sound_data.json", 'r') as f:
            data = json.load(f)
        return {int(k): b64decode(v) for k, v in data.items()}
    except Exception as e:
        print(f"加载音频数据失败: {e}")
        return {}

SOUND_DATA = load_sound_data()

def play_sound(index):
    """从内存播放音频"""
    if index not in SOUND_DATA:
        return
    
    try:
        sound_data = io.BytesIO(SOUND_DATA[index])
        sound = pygame.mixer.Sound(sound_data)
        sound.play()
    except Exception as e:
        print(f"播放失败: {e}")

def play_sound(index):
    """直接从内存播放音频"""
    try:
        sound_data = io.BytesIO(SOUND_DATA[index])
        sound = pygame.mixer.Sound(sound_data)
        sound.play()
    except Exception as e:
        print(f"播放失败: {e}")

# 创建主窗口
root = tk.Tk()
root.title("京剧电子锣鼓 v2.0")
root.configure(bg="#1E1E1E")

# 键盘映射配置（QWERTY布局）
KEY_BINDINGS = {
    'q': 0, 'w': 1, 'e': 2, 'r': 3,
    'a': 4, 's': 5, 'd': 6, 'f': 7,
    'h': 8, 'j': 9, 'k': 10, 'l': 11
}

# 按钮样式配置
BUTTON_STYLE = {
    'bg': '#3A3A3A',
    'fg': 'white',
    'activebackground': '#5A5A5A',
    'font': ('楷体', 12, 'bold'),
    'borderwidth': 3,
    'relief': 'raised',
    'width': 14,
    'height': 2
}

# 乐器名称与快捷键显示
INSTRUMENTS = [
    ('七', 'Q'), ('仓', 'W'),
    ('令', 'E'), ('八', 'R'),
    ('台', 'A'), ('嘟', 'S'),
    ('多', 'D'), ('大', 'F'),
    ('才', 'H'), ('扑', 'J'),
    ('本', 'K'), ('顷', 'L')
]

# 3x4网格布局
for row in range(3):
    root.rowconfigure(row, weight=1, minsize=100)
    for col in range(4):
        root.columnconfigure(col, weight=1, minsize=150)
        index = row * 4 + col
        if index >= 12:
            break
        
        # 创建带快捷键提示的按钮
        text = f"{INSTRUMENTS[index][0]}\n[{INSTRUMENTS[index][1]}]"
        btn = tk.Button(root, text=text, **BUTTON_STYLE,
                        command=lambda idx=index: play_sound(idx))
        btn.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")

# 键盘事件绑定
def on_key_press(event):
    if event.char.lower() in KEY_BINDINGS:
        play_sound(KEY_BINDINGS[event.char.lower()])

root.bind("<KeyPress>", on_key_press)

# 全屏提示
root.geometry("800x600")
root.resizable(False, False)

# 运行主循环
root.mainloop()
